<?php
namespace app\classes\helper;
use think\Db;

class ReportOrder
{
    /*
     * 订单上报过滤
     * */
    public function report_filtering($orderInfo)
    {
        $field = "advert_media_id,report_ab,report_ao,report_old_fans,report_caliber,report_full,order_amount_below,order_amount_above,hourValue";
        $field .= ",report_order_bn,misreporting_type,misreporting_percentage,misreporting_loop_proportion,status,vip_order_switch";

        $stop_time = strtotime('2024-06-03 00:00:00');

        $field_order = "id,order_id,uid,quick_id,total_fee,channel_id,create_time,update_time,create_date,user_reg_date,recharge_type,type,recharge_times,advert_media_id,nid";

        $order = Db::table('pay_order_success')->where('id',$orderInfo['id'])
                    ->where('is_report',1)
                    ->field($field_order)
                    ->findOrEmpty();

        /*if($order['advert_media_id'] == 1 && time() >= $stop_time)
        {
            $ReportOrder->report_mark($order['channel_id'],$order['id'],'快手端口回传关闭',$order['order_id']);
            return false;
        }*/

        $media_name = getAdvertMediaName($order['advert_media_id']);

        $recordAdvert = Db::table('pay_order_advert')->where('order_id',$order['order_id'])
            ->field('order_id,behavior_id,aid')->find();

        if(empty($recordAdvert))
        {
            $this->report_mark($order['channel_id'],$order['id'],'无匹配广告行为',$order['order_id']);
            return false;
        }

        $recordLink = Db::table('quick_backhaul_link')->where('advert_media_id',$order['advert_media_id'])
            ->where('channel_id',$order['channel_id'])
            ->field($field)
            ->findOrEmpty();

        if(empty($recordLink))
        {
            $this->report_mark($order['channel_id'],$order['id'],'投放号未设置【'.$media_name.'】媒体回传',$order['order_id']);
            return false;
        }

        if($recordLink['status'] != 1)
        {
            $this->report_mark($order['channel_id'],$order['id'],'投放号【'.$media_name.'】媒体回传未启用',$order['order_id']);
            return false;
        }

        if($recordLink['report_ao'] == 2 && $order['recharge_type'] == 2)
        {
            $this->report_mark($order['channel_id'],$order['id'],'活动订单不上报',$order['order_id']);
            return false;
        }

        if($recordLink['report_caliber'] == 1)
        {
            //激活X小时内第一笔成功充值
            $regtime = Db::table('quick_user')->where('id',$order['uid'])->value('regtime');
            $reg_end_time       = strtotime($regtime)+$recordLink['hourValue']*3600;
            $cur_time           = time();

            if( !($cur_time <= $reg_end_time && $order['recharge_times'] == 1) )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-1',$order['order_id']);
                return false;
            }

        }

        if($recordLink['report_caliber'] == 2)
        {
            //激活当天X小时内第一笔成功充值
            $regtime = Db::table('quick_user')->where('id',$order['uid'])->value('regtime');
            $reg_end_time       = strtotime($regtime)+$recordLink['hourValue']*3600;
            $cur_time           = time();
            $that_end_time      = strtotime(date('Y-m-d 23:59:59',strtotime($regtime)));
            $reg_end_time       = $reg_end_time > $that_end_time ? $that_end_time : $reg_end_time;

            if( !($cur_time <= $reg_end_time && $order['recharge_times'] == 1) )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-2',$order['order_id']);
                return false;
            }
        }

        if($recordLink['report_caliber'] == 3)
        {
            //激活后X小时内所有成功充值
            $regtime = Db::table('quick_user')->where('id',$order['uid'])->value('regtime');
            $reg_end_time       = strtotime($regtime)+$recordLink['hourValue']*3600;
            $cur_time           = time();

            if( !($cur_time <= $reg_end_time ) )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-3',$order['order_id']);
                return false;
            }
        }

        if($recordLink['report_caliber'] == 4)
        {
            //激活当天X小时内的所有成功充值
            $regtime = Db::table('quick_user')->where('id',$order['uid'])->value('regtime');
            $reg_end_time       = strtotime($regtime)+$recordLink['hourValue']*3600;
            $cur_time           = time();
            $that_end_time      = strtotime(date('Y-m-d 23:59:59',strtotime($regtime)));
            $reg_end_time       = $reg_end_time > $that_end_time ? $that_end_time : $reg_end_time;

            if( !($cur_time <= $reg_end_time) )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-4',$order['order_id']);
                return false;
            }
        }

        if($recordLink['report_caliber'] == 5)
        {
            //上报进入广告X小时内用户首充
            $behavior_time = Db::table('quick_user_behavior_monitoring')
                ->where('id',$recordAdvert['behavior_id'])->value('create_time');

            $behavior_end_time  = strtotime($behavior_time)+$recordLink['hourValue']*3600;
            $cur_time           = time();

            if( !($cur_time <= $behavior_end_time && $order['recharge_times'] == 1 )  )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-5',$order['order_id']);
                return false;
            }

        }

        if($recordLink['report_caliber'] == 6)
        {
            //上报进入广告当天X小时内用户首充
            $behavior_time = Db::table('quick_user_behavior_monitoring')
                ->where('id',$recordAdvert['behavior_id'])->value('create_time');

            $behavior_end_time  = strtotime($behavior_time)+$recordLink['hourValue']*3600;
            $cur_time           = time();
            $that_end_time      = strtotime(date('Y-m-d 23:59:59',strtotime($behavior_time)));
            $behavior_end_time  = $behavior_end_time > $that_end_time ? $that_end_time : $behavior_end_time;

            if( !($cur_time <= $behavior_end_time && $order['recharge_times'] == 1 )  )
            {
                $this->report_mark($order['channel_id'],$order['id'],'上报口径不符-6',$order['order_id']);
                return false;
            }

        }

        if(strlen($recordLink['order_amount_below']) >= 1 && $recordLink['order_amount_below'] > 0)
        {
            $order_amount_below = $recordLink['order_amount_below']*100;
            if($order['total_fee'] <= $order_amount_below)
            {
                $this->report_mark($order['channel_id'],$order['id'],'订单金额不符-'.$recordLink['report_caliber'],$order['order_id']);
                return false;
            }
        }

        $order_amount_above = $recordLink['order_amount_above']*100;
        if ($order['total_fee'] >= $order_amount_above) {
            $this->report_mark($order['channel_id'], $order['id'], '订单金额不符-' . $recordLink['report_caliber'], $order['order_id']);
            return false;
        }

        if($recordLink['vip_order_switch'] == 1 && $order['type'] == 2)
        {
            $this->report_mark($order['channel_id'],$order['id'],'VIP会员订单不上报',$order['order_id']);
            return false;
        }

        $promotionReport = Db::table('pay_order_report_mark_promotion')
                    ->where('channel_id',$order['channel_id'])
                    ->where('promotion_id',$recordAdvert['aid'])
                    ->field('report_num,skip_num,all_report_num')->findOrEmpty();

        $order_skip_num = $promotionReport ? $promotionReport['skip_num'] : 0; //跳过笔数
        $order_report_num = $promotionReport ? $promotionReport['report_num'] : 0; //上报笔数
        $report = false;

        if($recordLink['report_full'] == 2)
        {
            /*回传部分订单 --start--*/
            if( (empty($promotionReport) && $recordLink['report_order_bn'] > 0) || ($promotionReport && $promotionReport['all_report_num'] < $recordLink['report_order_bn']) )
            {
                //每日先回传笔数
                $this->report($order,$recordAdvert['behavior_id'],$order_report_num,$promotionReport,$recordAdvert);
            }else{

                if($recordLink['misreporting_type'] == 1)
                {
                    //百分比回传
                    $rand_num = rand(1,100);
                    if($rand_num <= $recordLink['misreporting_percentage'])
                    {
                        $this->report($order,$recordAdvert['behavior_id'],$order_report_num,$promotionReport,$recordAdvert);
                    }else{
                        $this->report_mark($order['channel_id'],$order['id'],'概率忽略',$order['order_id']);
                        return false;
                    }

                }else{
                    //循环比例回传
                    list($report_num_ps,$skip_num_ps) = explode(':',$recordLink['misreporting_loop_proportion']);
                    //echo $order_report_num.'---'.$report_num_ps.'已上报笔数-比例设置上报笔数'.PHP_EOL;

                    if($order_report_num < $report_num_ps)
                    {

                        $this->report($order,$recordAdvert['behavior_id'],$order_report_num,$promotionReport,$recordAdvert);

                    }else{

                        if($order_skip_num > 0 )
                        {

                            //echo $order_skip_num.'---'.$skip_num_ps.'已跳过笔数-比例设置跳过笔数'.PHP_EOL;
                            if($order_skip_num < $skip_num_ps)
                            {
                                $skip_num_up = $order_skip_num + 1;
                                $report_num_up = $order_report_num;
                            }else{
                                $skip_num_up = 0;
                                $report_num_up = 1;
                                $this->report($order,$recordAdvert['behavior_id'],$order_report_num,$promotionReport,$recordAdvert);
                                $report = true;
                            }

                        }else{

                            $skip_num_up = $order_skip_num + 1;
                            $report_num_up = $order_report_num;
                        }

                        if($promotionReport)
                        {
                            Db::table('pay_order_report_mark_promotion')
                                ->where('promotion_id',$recordAdvert['aid'])
                                ->where('channel_id',$order['channel_id'])
                                ->update([
                                    'skip_num'=>$skip_num_up,'report_num'=>$report_num_up
                                ]);
                        }else{
                            Db::table('pay_order_report_mark_promotion')
                                ->insert([
                                    'channel_id'=>$order['channel_id'],'promotion_id' => $recordAdvert['aid'],
                                    'skip_num'=>$skip_num_up,'report_num'=>$report_num_up,
                                    'all_report_num' => $report_num_up > 0 ? 1 : 0,
                                ]);
                        }

                        if(!$report)
                        {
                            $this->report_mark($order['channel_id'],$order['id'],'概率忽略',$order['order_id']);
                            return false;
                        }


                    }
                }

            }
            /*回传部分订单 --end--*/
        }else{
            //全量回传
            $this->report($order,$recordAdvert['behavior_id'],$order_report_num,$promotionReport,$recordAdvert);
        }


    }

    /*
     * 订单上报
     * */
    public function report($order,$behavior_id,$order_report_num,$promotionReport,$recordAdvert)
    {
        $reportResult = [];

        $behavior = Db::table('quick_user_behavior_monitoring')->where('id',$behavior_id)
            ->field('ip_addr,link,adsign')->findOrEmpty();

        if($order['advert_media_id'] == 1)
        {
            //3付费 1激活 2注册
            $event_type = 3;
            $reportResult = $this->ks_report($order,$behavior,$event_type);
        }

        if($order['advert_media_id'] == 3)
        {
            //2付费 0激活 1注册
            $event_type = 2;
            $reportResult = $this->jl_report($order,$behavior,$event_type);
        }

        if($order['advert_media_id'] == 4)
        {
            //pay_to_read：付费阅读 activate：激活
            $event_type = 'pay_to_read';
            $reportResult = $this->baidu_report($order,$behavior,$event_type);
        }

        if($order['advert_media_id'] == 5){
            //2付费 0激活 1注册
            $event_type = 2;
            $reportResult = $this->uc_report($order,$behavior,$event_type);
        }


        if($order['advert_media_id'] == 6){
            //1激活 2付费
            $event_type = 2;
            $reportResult = $this->vivo_report($order,$behavior,$event_type);
        }

        if($order['advert_media_id'] == 7){
            //1激活 2付费
            $event_type = 2;
            $reportResult = $this->oppo_report($order,$behavior,$event_type);
        }


        if($order['advert_media_id'] == 8){
            //1激活 2付费
            $event_type = 2;
            $reportResult = $this->bilibili_report($order,$behavior,$event_type);
        }

        $media_name = getAdvertMediaName($order['advert_media_id']);

        if(empty($reportResult))
        {
            $this->report_mark($order['channel_id'],$order['id'],"{$media_name}未接入上报",$order['order_id']);
            return true;
        }

        if($reportResult['code'] == 100)
        {
            $report_num_up = $order_report_num + 1;
            if($promotionReport)
            {
                Db::table('pay_order_report_mark_promotion')
                    ->where('promotion_id',$recordAdvert['aid'])
                    ->where('channel_id',$order['channel_id'])->update([
                        'report_num'=>$report_num_up
                    ]);

                Db::table( 'pay_order_report_mark_promotion')
                    ->where( 'promotion_id', $recordAdvert['aid'])
                    ->where( 'channel_id',$order['channel_id'])->setInc('all_report_num');
            }else{
                Db::table('pay_order_report_mark_promotion')->insert([
                    'channel_id'=>$order['channel_id'],'report_num'=>$report_num_up,
                    'promotion_id'=>$recordAdvert['aid'],'all_report_num'=>1
                ]);
            }

            $report_daily = Db::table('pay_order_report_mark_daily')->where('channel_id',$order['channel_id'])
                ->where('create_date',date('Y-m-d'))
                ->where('promotion_id',$recordAdvert['aid'])
                ->field('id')->findOrEmpty();

            if($report_daily)
            {
                Db::table('pay_order_report_mark_daily')->where('channel_id',$order['channel_id'])
                    ->where('create_date',date('Y-m-d'))
                    ->where('promotion_id',$recordAdvert['aid'])
                    ->setInc('report_num', 1);

            }else{
                Db::table('pay_order_report_mark_daily')->insert([
                    'channel_id'=>$order['channel_id'],'report_num'=>1,
                    'promotion_id'=>$recordAdvert['aid'],
                    'create_date'=>date('Y-m-d')
                ]);
            }

            Db::table('pay_order')->where('id',$order['order_id'])->update(['is_report'=>2]);
            Db::table('pay_order_success')->where('order_id',$order['order_id'])->update(['is_report'=>2]);
        }else{
            Db::table('pay_order')->where('id',$order['order_id'])->update(['is_report'=>3]);
            Db::table('pay_order_success')->where('order_id',$order['order_id'])->update(['is_report'=>3]);
        }

        $this->report_mark($order['channel_id'],$order['id'],$reportResult['message'],$order['order_id']);
    }

    /*更新订单上报标记*/
    public function report_mark($channel_id,$order_id_mark,$msg,$order_id)
    {
        $record = Db::table('pay_order_report_mark')->where('channel_id',$channel_id)->field('id')
            ->findOrEmpty();

        if($record){
            Db::table('pay_order_report_mark')->where('id',$record['id'])->update(['order_id'=>$order_id_mark]);
        }else{
            Db::table('pay_order_report_mark')->insert(['order_id'=>$order_id_mark,'channel_id'=>$channel_id]);
        }

        Db::table('pay_order_advert')->where('order_id',$order_id)->update(['report_result'=>$msg]);

    }

    /*快手广告订单上报*/
    private function ks_report($order,$behavior,$event_type)
    {
        if(empty($behavior))
        {
            if($event_type == 3)
            {
                $order['event_type'] = 'active_pay';
            }
            if($event_type == 1){
                $order['event_type'] = 'active';
            }

            $params = $this->getParams($order);
            $response = ['code'=>102,'message'=>'上报失败'];
            $this->addBackhaulLog($params,$response,'');
            return $response;
        }

        // 上报数据 拼接
        if($event_type == 3)
        {
            $order['event_type'] = 'active_pay';
            $event_time         = strtotime($order['create_time'])*1000;
            $purchase_amount    = $order['total_fee']/100;
            $apiUrl             = $behavior['link'].'&event_type='.$event_type.'&event_time='.$event_time.'&purchase_amount='.$purchase_amount;
        }

        if($event_type == 1){
            $order['event_type'] = 'active';
            $event_time         = strtotime($order['active_time'])*1000;
            $apiUrl             = $behavior['link'].'&event_type='.$event_type.'&event_time='.$event_time;
        }

        //若为落地页进入的不带上报地址的callback，需要补全上报地址
        if(!isHttpUrl($behavior['link'])){
            $apiUrl = 'http://ad.partner.gifshow.com/track/activate?callback='.$apiUrl;
        }

        $params = $this->getParams($order);

        $result_str = httpGet($apiUrl);
        $result     = json_decode($result_str, true);

        if ($result['result'] == 1) {
            $response = ['code'=>100,'message'=>'上报成功'];
            $this->addBackhaulLog($params,$response,$apiUrl);
        } else {
            $response = ['code'=>102,'message'=>'上报失败'];
            $this->addBackhaulLog($params,$response,$apiUrl);
        }

        return $response;
    }

    /*巨量二跳订单上报*/
    private function jl_report($order,$behavior,$event_type)
    {

        if(empty($behavior))
        {
            if($event_type == 0)
            {
                $order['event_type'] = 'active';
            }
            if($event_type == 2)
            {
                $order['event_type'] = 'active_pay';
            }

            $params = $this->getParams($order);
            $response = ['code'=>102,'message'=>'上报失败'];
            $this->addBackhaulLog($params,$response,'');
            return $response;
        }

        $behaviorInfo = json_decode($behavior['link'], true);

        if($event_type == 0)
        {
            $order['event_type'] = 'active';
            $thetime = strtotime($order['active_time']);
            $apiUrl = 'https://ad.oceanengine.com/track/activate?callback=' . urlencode($behaviorInfo['callback']) . '&conv_time=' . $thetime . '&event_type='.$event_type;
        }

        if($event_type == 2)
        {
            $order['event_type'] = 'active_pay';
            $money = $order['total_fee'] ? $order['total_fee'] / 100 : 0;
            $thetime = strtotime($order['create_time']);
            $apiUrl = 'https://ad.oceanengine.com/track/activate?callback=' . urlencode($behaviorInfo['callback']) . '&props='.urlencode('{"pay_amount":'.$money.'}').'&conv_time=' . $thetime . '&event_type='.$event_type;
        }

        $params = $this->getParams($order);

        // 上报数据

        try {
            $result = httpGet($apiUrl);
            $result = json_decode($result, true);
        } catch (\Exception $e) {
            $this->addBackhaulLog($params,1,$apiUrl);
        }

        if (isset($result['code']) && $result['code'] == 0) {
            $response = ['code'=>100,'message'=>'上报成功'];
            $this->addBackhaulLog($params,$response,$apiUrl);
        } else {
            $response = ['code'=>102,'message'=>'上报失败'];
            $this->addBackhaulLog($params,$response,$apiUrl);
        }

        return $response;
    }

    /*百度订单上报*/
    private function baidu_report($order, $behavior, $event_type)
    {
        if ($event_type == 'pay_to_read')
        {
            $order['event_type'] = 'active_pay';
        }else{
            $order['event_type'] = 'active';
        }

        if (empty($behavior)) {
            $params = $this->getParams($order);
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        ////2付费 0激活 1注册
        if ($event_type == 'pay_to_read') {
            $avalue = $order['total_fee'];
        } else {
            $avalue = 0;
        }
        $behaviorInfo = json_decode($behavior['link'], true);
        $behaviorUrl = $behaviorInfo['callback_url'];
        $params = $this->getParams($order);

        $apiUrl = str_replace("{{ATYPE}}", $event_type, $behaviorUrl);
        $apiUrl = str_replace("{{AVALUE}}", $avalue, $apiUrl);

        $akey = Db::table('quick_ad_account_baidu')->where(['mysign' => strval($behavior['adsign'])])->value('akey');
        $bookName = '无';
        $payCatalogGender = '无';
        $payCatalog = '无';
        //书籍id大于0的查询对应书籍信息
        if ($order['nid'] > 0) {
            $bookinfo = Db::table("novel")->where('id', $order['nid'])->cache(3600)->field('title,freq_id,class_id')->find();
            if ($bookinfo) {
                $payCatalogGender = Db::table("novel_freq")->where("id", $bookinfo['freq_id'])->cache(3600)->value('name') ?? '无';
                $payCatalog = Db::table("novel_class")->where("id", $bookinfo['class_id'])->cache(3600)->value('name') ?? '无';
                $bookName = $bookinfo['title'];
            }
        }
        if ($event_type == 'pay_to_read') {
            //发生转化时间（精确到毫秒）
            $order_at = $order_at = isset($order['update_time']) ? $order['update_time'] : $order['create_time'];
        } else {
            $order_at = $order['active_time'];
        }
        $cb_event_time = strtotime($order_at) * 1000;
        $apiUrl = $apiUrl . '&bookName=' . urlencode($bookName) . '&payCatalogGender=' . urlencode($payCatalogGender) . '&payCatalog=' . urlencode($payCatalog) . '&cb_event_time=' . $cb_event_time;

        $sign = md5($apiUrl . $akey);
        $apiUrl = $apiUrl . '&sign=' . $sign;
        // 上报数据
        try {
            $result_str = file_get_contents($apiUrl);
            $result = json_decode($result_str, true);

        } catch (\Exception $e) {
            $this->addBackhaulLog($params, 1, $apiUrl);
        }

        if (isset($result['error_code']) && $result['error_code'] == 0) {
            $response = ['code' => 100, 'message' => '上报成功'];
            $this->addBackhaulLog($params, $response, $apiUrl);
        } else {
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, $apiUrl);
        }
        return $response;
    }


    /*uc订单上报*/
    private function uc_report($order, $behavior, $event_type)
    {
        if ($event_type == 2)
        {
            $order['event_type'] = 'active_pay';
        }else{
            $order['event_type'] = 'active';
        }

        if (empty($behavior)) {
            $params = $this->getParams($order);
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        $params = $this->getParams($order);
        $behaviorUrl = $behavior['link'];
        if ($event_type == 2) {
            $order_at = $order_at = isset($order['update_time']) ? $order['update_time'] : $order['create_time'];
            $apiUrl = $behaviorUrl . '&type=69&event_time=' . strtotime($order_at) . '&money=' . ($order['total_fee'] / 100);
        } else {
            $order_at = $order['active_time'];
            $apiUrl = $behaviorUrl . '&type=68&event_time=' . strtotime($order_at) ;
        }
        // 上报数据
        try {
            $result = $this->httpGetCode($apiUrl);
        } catch (\Exception $e) {
            $this->addBackhaulLog($params, 1, $apiUrl);
        }

        if (isset($result) && $result == 200) {
            $response = ['code' => 100, 'message' => '上报成功'];
            $this->addBackhaulLog($params, $response, $apiUrl);
        } else {
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, $apiUrl);
        }
        return $response;
    }


    /*vivo订单上报*/
    private function vivo_report($order, $behavior, $event_type)
    {
        if ($event_type == 2)
        {
            $order['event_type'] = 'active_pay';
        }else{
            $order['event_type'] = 'active';
        }

        if (empty($behavior)) {
            $params = $this->getParams($order);
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        $params = $this->getParams($order);
        $behaviorInfo = json_decode($behavior['link'], true);
        $vivoConfig = Db::table("quick_ad_account_vivo")->where("mysign", $behaviorInfo['mysign'])->cache(3600)->field("akey,token,advertiser_id")->find();
        if (!$vivoConfig){
            $response = ['code' => 102, 'message' => '上报失败，无vivo账号'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        $srcId = $vivoConfig['akey'];
        $access_token = $vivoConfig['token'];
        $advertiser_id = $vivoConfig['advertiser_id'];
        $creativeId = isset($behaviorInfo['creativeId']) ? $behaviorInfo['creativeId'] : '';//1695720769823_09ee5a0237064fb6b7be02c3bd623448
        $reqId = isset($behaviorInfo['reqId']) ? $behaviorInfo['reqId'] : '';//47491038

        if ($event_type == 2) {
            $order_at = $order_at = isset($order['update_time']) ? $order['update_time'] : $order['create_time'];
        } else {
            $order_at = $order['active_time'];
        }
        $msectime = strtotime($order_at)*1000;
        $nonce = md5($order['id'] ."_". rand(1, 100000) ."_". time());
        $packageName = Db::table("quick_app")->where("id",$order['quick_id'])->cache("3600")->value('package_name');
        $url = 'https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload?access_token=' . $access_token . '&timestamp=' . $msectime . '&nonce=' . $nonce;
        if ($advertiser_id){
            $url .= "&advertiser_id=".$advertiser_id;
        }
        if ($event_type == 2){
            $cvType = 'PAY';
        }else{
            $cvType = 'ACTIVATION';
        }
        $data = [
            'srcType' => 'Quickapp',
            'pkgName' => trim($packageName),
            'pageUrl' => 'read',
            'srcId' => $srcId,
            'dataList' => [
                'cvType' => $cvType,
                'cvTime' => $msectime,
                'requestId' => $reqId,
                'creativeId' => $creativeId
            ],
        ];
        // 上报数据
        $res = httpPost($url, json_encode($data));
        $result = json_decode($res, true);
        if (isset($result) && $result['code'] == 0) {
            $response = ['code' => 100, 'message' => '上报成功'];
            $this->addBackhaulLog($params, $response, json_encode($data,JSON_UNESCAPED_UNICODE));
        } else {
            $response = ['code' => 102, 'message' => '上报失败'];
            $logData = [
                'url' => $url,
                'param' => $data,
                'res' => $res,
            ];
            $this->addBackhaulLog($params, $response, json_encode($logData,JSON_UNESCAPED_UNICODE));
        }
        return $response;
    }


    /*oppo订单上报*/
    private function oppo_report($order, $behavior, $event_type)
    {
        if ($event_type == 2)
        {
            $order['event_type'] = 'active_pay';
        }else{
            $order['event_type'] = 'active';
        }

        $params = $this->getParams($order);
        if (empty($behavior)) {
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        $behaviorInfo = json_decode($behavior['link'], true);
        $apiUrl = 'https://api.ads.heytapmobi.com/api/uploadActiveData';
        if ($event_type == 2) {
            $order_at = isset($order['update_time']) ? $order['update_time'] : $order['create_time'];
        } else {
            $order_at = $order['active_time'];
        }
        $timestamp = strtotime($order_at) * 1000;
        $packageName = Db::table("quick_app")->where("id",$order['quick_id'])->cache("3600")->value('package_name');
        $dataType = 16;
        if ($event_type != 2){
            $dataType = 1;
        }
        $body = [
            'imei' => '',//客户端 imei 经过 AES 加密后的值 如 868123039927020=>XJMyaLt8fDlv4a9b8/0RNQ==
            'ouId' => '',//开发者ID经过AES加密后的值 ouId  就是 oaid 优先使用imei
            'clientIp' => $behavior['ip_addr'],//(否)事 件 发 生 时 的 客 户 端 ip
            'timestamp' => $timestamp,//事件发生的时间戳(毫秒)
            'pkg' => $packageName,//包名，如 com.xxx 或 快应用 id，如 100137
            'dataType' => $dataType,//1、激活，2、注册 16、快应用付费 19、快应用关键行为
            'customType' => '',//自定义目标类型：dataType 填了 8之后补充，枚举值与客户沟通后补充
            'channel' => 1,//渠道：1、OPPO，2、一加，0、其他
            'type' => 2,//0：无加密（默认为 0）1：imei md5 加密 2：oaid md5 加密
            'appType' => 3,//应用类别：1 应用 2 游戏 3 快应用 0 其他，默认 1 应用
            'payAmount' => isset($order['total_fee']) ? $order['total_fee'] : 0,//付费金额（单位：分 ）
            'ascribeType' => 1,//归因类型：1：广告主归因，0：OPPO归因（默认或者不填即为 0），2：助攻归因
            'adId' => $behaviorInfo['cid'],//广告主回传转化数据时，附带已经归因好的广告 id
            'requestId' => $behaviorInfo['req_id']//(否)请求 id
        ];
        if($behaviorInfo['oaid']){
            $body['ouId'] = $this->oppoEncrypt($behaviorInfo['oaid']);
            $body['type'] = 2;
        }
        if($behaviorInfo['imei']){
            $body['imei'] = $this->oppoEncrypt($behaviorInfo['imei']);
            $body['type'] = 1;
        }
        $postData = json_encode($body);
        $salt = 'e0u6fnlag06lc3pl';
        $signature = md5($postData.$timestamp.$salt);
        $header = [
            'signature:'.$signature
            ,'timestamp:'.$timestamp
            ,'Content-Type:'.'application/json'
        ];

        // 上报数据
        try {
            $result_str = jhCurl($apiUrl, $postData, '1', $header);
            $result = json_decode($result_str, true);
        } catch (\Exception $e) {
            $this->addBackhaulLog($params, 1, $postData);
        }
        if (isset($result) && $result['ret'] == 0) {
            $response = ['code' => 100, 'message' => '上报成功'];
            $this->addBackhaulLog($params, $response, $postData);
        } else {
            $response = ['code' => 102, 'message' => '上报失败'];
            $this->addBackhaulLog($params, $response, $postData);
        }
        return $response;
    }



    /*bilibili订单上报*/
    private function bilibili_report($order, $behavior, $event_type)
    {
        if ($event_type == 2)
        {
            $order['event_type'] = 'active_pay';
        }else{
            $order['event_type'] = 'active';
        }

        $params = $this->getParams($order);
        if (empty($behavior)) {
            $response = ['code' => 102, 'message' => '无广告行为'];
            $this->addBackhaulLog($params, $response, '');
            return $response;
        }
        $behaviorInfo = json_decode($behavior['link'], true);
        if ($event_type == 2) {
            $order_at = $order_at = isset($order['update_time']) ? $order['update_time'] : $order['create_time'];
        } else {
            $order_at = $order['active_time'];
        }
        if ($event_type == 2) {
            $conv_type = 'USER_COST';
        } else {
            $conv_type = 'APP_FIRST_ACTIVE';
        }
        $conv_time = strtotime($order_at) * 1000;
        $track_id = $behaviorInfo['track_id'];
        $url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type={$conv_type}&conv_time={$conv_time}&track_id={$track_id}";
        if (isset($behaviorInfo['oaidmd5']) && $behaviorInfo['oaidmd5'] && $behaviorInfo['oaidmd5'] != '__OAIDMD5__') {
            $url .= "&oaid={$behaviorInfo['oaidmd5']}";
        }
        // 上报数据
        $res = httpGet($url);
        $result = json_decode($res, true);
        if (isset($result) && $result['code'] == 0) {
            $response = ['code' => 100, 'message' => '上报成功'];
            $this->addBackhaulLog($params, $response, $url);
        } else {
            $response = ['code' => 102, 'message' => '上报失败'];
            $logData = [
                'url' => $url,
                'param' => [],
                'res' => $res,
            ];
            $this->addBackhaulLog($params, $response, json_encode($logData, JSON_UNESCAPED_UNICODE));
        }
        return $response;
    }


    //oppo的 AES加密
    private function oppoEncrypt($input, $base64Key = 'XGAXicVG5GMBsx5bueOe4w=='){
        return openssl_encrypt($input, 'AES-128-ECB',base64_decode($base64Key),0,'');
    }

    //获取请求状态码
    private function httpGetCode($url){
        $curl = curl_init();

        // 设置 cURL 选项
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5); // 设置请求超时时间为 10 秒
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); // 设置连接超时时间为 5 秒
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        // 执行 cURL 请求
        $res = curl_exec($curl);

        // 检查是否有错误发生
        if ($res === false) {
            // $error = curl_error($curl);
            // 在这里，您可以记录错误，或者选择抛出异常，或者执行其他错误处理逻辑
            // 例如：throw new Exception("cURL Error: " . $error);
            return false; // 或者返回 null，或者一个错误代码，这取决于您的错误处理策略
        }

        // 获取 HTTP 状态码
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // 关闭 cURL 资源
        curl_close($curl);

        return $httpCode;
    }

    /*广点通广告订单上报*/
    private function gdt_report($order,$behavior)
    {

    }

    // 回传日志写入
    private function addBackhaulLog($params,$response,$request_data)
    {
        $data['channel_id']     = $params['channel_id'];
        $data['uid']            = $params['uid'];
        $data['bl_id']          = $params['bl_id'];
        $data['type']           = $params['btype'];
        $data['request_data']   = $request_data;
        $data['response']       = json_encode($response,JSON_UNESCAPED_UNICODE);

        Db::table('quick_backhaul_log')->insert($data);

    }

    /*回传日志参数相关组装*/
    private function getParams($order)
    {
        $blink = Db::table('quick_backhaul_link')
            ->where('channel_id',$order['channel_id'])
            ->where('advert_media_id',$order['advert_media_id'])
            ->field('id,advert_media_id,channel_id,report_ab,report_jb,report_rb,report_ao,report_old_fans')
            ->findOrEmpty();

        //if ($order['event_type'] == 2 || $order['event_type'] == 'active_pay' || $order['event_type'] == 'pay_to_read') {

        if ($order['event_type'] == 'active_pay')
        {
            $btype = 2;

        } else if ($order['event_type'] == 'active') {

            $btype = 1;
        } else {
            $btype = 0;
        }

        $params['channel_id']   = $blink['channel_id'];
        $params['uid']          = $order['uid'];
        $params['bl_id']        = $blink['id'];
        $params['btype']        = $btype;

        return $params;
    }

}